﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.LowPriceHouse;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Models.StaffApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.StaffAPI
{
    public class StaffLowPriceHouseRunningsController : BaseApiController
    {
        public IBrokerageRunningsContract BrokerageRunningsContract { set; get; }// 佣金流水
        public IStaffContract StaffContract { get; set; }
        public ILowPriceHouseRunningsContract LowPriceHouseRunningsContract { get; set; }
        public ILowPriceHouseRunningsStateContract LowPriceHouseRunningsStateContract { get; set; }
        public IImagesContract ImagesContract { get; set; }






        [Description("API-报备审批列表")]
        public IHttpActionResult ttGetFilingList()
        {
            var staffModel = StaffContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());

            var query = from n in LowPriceHouseRunningsContract.Entities

                        join s1 in StaffContract.Entities on n.OriginStaffID equals s1.Id into eu1//渠道人员
                        from eu1d in eu1.DefaultIfEmpty()

                        join s2 in StaffContract.Entities on n.SellStaffID equals s2.Id into eu2//销售人员
                        from eu2d in eu2.DefaultIfEmpty()

                        join m in LowPriceHouseRunningsStateContract.Entities on n.State equals m.Id into eu3//流程状态
                        from eu3d in eu3.DefaultIfEmpty()

                        where n.State == 1 && n.AgentID == staffModel.AgentID

                        select new LowPriceHouseRunningsListModel
                        {
                            BandSawTime = n.BandSawTime,
                            BuildingID = n.LowPriceHouseID,
                            BuildingName = n.BuildingName == null ? "" : n.BuildingName,
                            CompleteTime = n.CompleteTime,
                            CustomerID = n.CustomerID,
                            CustomerName = n.CustomerName == null ? "" : n.CustomerName,
                            CustomerPhone = n.CustomerPhone == null ? "" : n.CustomerPhone,
                            DownPaymentTime = n.DownPaymentTime,
                            FilingTime = n.FilingTime,
                            Id = n.Id,
                            IntermediaryID = n.IntermediaryID,
                            IntermediaryName = n.IntermediaryName == null ? "" : n.IntermediaryName,
                            OriginStaffID = n.OriginStaffID,
                            OriginStaffName = eu1d.Name == null ? "" : eu1d.Name,
                            PutOnRecordTime = n.PutOnRecordTime,
                            Remark = n.State == 3 ? n.FilingAuditingRemark : n.Remark,
                            SellStaffID = n.SellStaffID,
                            SellStaffName = eu2d.Name == null ? "" : eu2d.Name,
                            State = n.State,
                            StateName = eu3d.Name == null ? "" : eu3d.Name,
                            SubscribeTime = n.SubscribeTime,
                            TotalPrice = 0,//暂时没用
                            UserID = n.UserID,
                            UserName = n.UserName == null ? "" : n.UserName,
                            UserPhone = n.UserPhone == null ? "" : n.UserPhone,
                            BandSawImageNumber = 0,
                            PutOnRecordImageNumber = 0,
                            SubscribeImageNumber = 0,
                        };

            var result = new AjaxResult("成功", AjaxResultType.Success, query.ToList());
            return Token(result, "");
        }


        [Description("API-历史列表")]
        public IHttpActionResult ttGetLowPriceHouseRunningsList([FromBody]LowPriceHouseRunningsParamsModel entity)
        {
            DateTime bt = entity.BeginTime;
            DateTime et = entity.EndTime.AddDays(1);

            var staffModel = StaffContract.GetByKey(BaseWebApiExt.GetStaffIDByToken());

            var query = from n in LowPriceHouseRunningsContract.Entities

                        join s1 in StaffContract.Entities on n.OriginStaffID equals s1.Id into eu1
                        from eu1d in eu1.DefaultIfEmpty()

                        join s2 in StaffContract.Entities on n.SellStaffID equals s2.Id into eu2
                        from eu2d in eu2.DefaultIfEmpty()

                        join m in LowPriceHouseRunningsStateContract.Entities on n.State equals m.Id into eu3
                        from s2d in eu3.DefaultIfEmpty()

                        where (n.OriginStaffID == staffModel.Id || n.SellStaffID == staffModel.Id) && n.SubscribeTime >= bt && n.SubscribeTime <= et && n.AgentID == staffModel.AgentID

                        select new LowPriceHouseRunningsListModel
                        {
                            BandSawTime = n.BandSawTime,
                            BuildingID = n.LowPriceHouseID,
                            BuildingName = n.BuildingName == null ? "" : n.BuildingName,
                            CompleteTime = n.CompleteTime,
                            CustomerID = n.CustomerID,
                            CustomerName = n.CustomerName == null ? "" : n.CustomerName,
                            CustomerPhone = n.CustomerPhone == null ? "" : n.CustomerPhone,
                            DownPaymentTime = n.DownPaymentTime,
                            FilingTime = n.FilingTime,
                            Id = n.Id,
                            IntermediaryID = n.IntermediaryID,
                            IntermediaryName = n.IntermediaryName == null ? "" : n.IntermediaryName,
                            OriginStaffID = n.OriginStaffID,
                            OriginStaffName = eu1d.Name == null ? "" : eu1d.Name,
                            PutOnRecordTime = n.PutOnRecordTime,
                            Remark = n.State == 3 ? (n.FilingAuditingRemark == null ? "" : n.FilingAuditingRemark) : (n.Remark == null ? "" : n.Remark),
                            SellStaffID = n.SellStaffID,
                            SellStaffName = eu2d.Name == null ? "" : eu2d.Name,
                            State = n.State,
                            StateName = s2d.Name == null ? "" : s2d.Name,
                            SubscribeTime = n.SubscribeTime,
                            TotalPrice = 0,
                            UserID = n.UserID,
                            UserName = n.UserName == null ? "" : n.UserName,
                            UserPhone = n.UserPhone == null ? "" : n.UserPhone,

                            BandSawImageNumber = ImagesContract.Entities.Count(p => p.GroupID == 5 && p.InterfixID == n.Id && p.ImageType == 1),//带看
                            SubscribeImageNumber = ImagesContract.Entities.Count(p => p.GroupID == 5 && p.InterfixID == n.Id && p.ImageType == 2),//成交
                            PutOnRecordImageNumber = ImagesContract.Entities.Count(p => p.GroupID == 5 && p.InterfixID == n.Id && p.ImageType == 3),//备案

                            BandSawImageList = ImagesContract.Entities.Where(x => x.GroupID == 5 && x.InterfixID == n.Id && x.ImageType == 1)//带看
                                   .Select(x => x.ImagePath + x.FileName)
                                   .ToList(),
                            SubscribeImageList = ImagesContract.Entities.Where(x => x.GroupID == 5 && x.InterfixID == n.Id && x.ImageType == 2)//成交
                                   .Select(x => x.ImagePath + x.FileName)
                                   .ToList(),
                            PutOnRecordImageList = ImagesContract.Entities.Where(x => x.GroupID == 5 && x.InterfixID == n.Id && x.ImageType == 3)//备案
                                   .Select(x => x.ImagePath + x.FileName)
                                   .ToList()
                        };

            string[] state = entity.State.Split(',');
            query = query.Where(p => state.Contains(p.State.ToString()));

            if (!String.IsNullOrEmpty(entity.Search))
            {
                query = query.Where(p => p.BuildingName.IndexOf(entity.Search) != -1 || p.IntermediaryName.IndexOf(entity.Search) != -1 || p.UserName.IndexOf(entity.Search) != -1 || p.CustomerName.IndexOf(entity.Search) != -1 || p.CustomerPhone.IndexOf(entity.Search) != -1 || p.UserPhone.IndexOf(entity.Search) != -1 || p.Id.ToString() == entity.Search);
            }

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.SubscribeTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.pageIndex - 1) * entity.pageSize).Take(entity.pageSize)
                : null;

            var result = new AjaxResult("成功", AjaxResultType.Success, (total > 0 ? query.ToList() : new List<LowPriceHouseRunningsListModel>()));
            return Token(result, "");
        }


        //==========================================================


        //State : 1 报备待审 2 报备通过 3 报备驳回 4 已带看 5 已交订金 6 已付首款 7 已备案 8 已完成
        //ReturnState : 1 默认 2 退房待审 3 已退房


        [Description("API-更新流程状态")]
        public IHttpActionResult ttUpdateRunningState([FromBody]AuditingStateParamsModel entity)
        {
            if (entity == null)
            {
                var result = new AjaxResult("审核失败", AjaxResultType.Error);
                return Token(result, "");
            }

            var query = LowPriceHouseRunningsContract.GetByKey(entity.Id);

            if (query == null)
            {
                var result = new AjaxResult("审核失败", AjaxResultType.Error);
                return Token(result, "");
            }

            try
            {
                //获取StaffID
                int staffid = BaseWebApiExt.GetStaffIDByToken();

                int count = 0;//更新结果

                if (query.ReturnState.Equals(1))//没退房
                {
                    int newState = query.State;

                    switch (query.State)
                    {
                        case 1://报备待审
                            if (entity.AuditingType.Equals(1))//同意
                            {
                                newState = 2;
                            }
                            else//不同意
                            {
                                newState = 3;
                            }
                            count = LowPriceHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new LowPriceHouseRunnings { State = newState, FilingAuditingStaffID = staffid, FilingAuditingRemark = entity.Remark, FilingAuditingTime = DateTime.Now });
                            break;
                        case 2://报备通过
                            newState = 4;
                            count = LowPriceHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new LowPriceHouseRunnings { State = newState, BandSawStaffID = staffid, BandSawTime = DateTime.Now });
                            break;
                        case 3://报备驳回
                            break;
                        case 4://已带看
                            newState = 5;
                            count = LowPriceHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new LowPriceHouseRunnings { State = newState, SubscribeStaffID = staffid, BargainMoney = entity.Money, SubscribeTime = DateTime.Now });
                            break;
                        case 5://已交订金
                            newState = 6;
                            count = LowPriceHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new LowPriceHouseRunnings { State = newState, DownPaymentStaffID = staffid, DownPaymentMoney = entity.Money, DownPaymentTime = DateTime.Now });
                            break;
                        case 6://已付首款
                            newState = 8;//已成交
                            count = LowPriceHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new LowPriceHouseRunnings { State = newState, CompleteStaffID = staffid, CompleteTime = DateTime.Now });
                            break;
                        case 7://已备案
                        case 8://已完成
                            break;
                        default:
                            break;
                    }
                }
                else//退房审核
                {
                    int newState2 = query.ReturnState;

                    switch (query.ReturnState)
                    {
                        case 1:
                            newState2 = 2;
                            count = LowPriceHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new LowPriceHouseRunnings { ReturnState = newState2, ReturnHouseStaffID = staffid, ReturnHouseTime = DateTime.Now });
                            break;
                        case 2:
                            if (entity.AuditingType.Equals(1))//同意
                            {
                                newState2 = 3;
                            }
                            else//不同意
                            {
                                newState2 = 1;
                            }
                            count = LowPriceHouseRunningsContract.UpdateDirect(m => m.Id.Equals(entity.Id), m => new LowPriceHouseRunnings { ReturnState = newState2, ReturnHouseAuditingStaffID = staffid, ReturnHouseAuditingRemark = entity.Remark, ReturnHouseAuditingTime = DateTime.Now });
                            break;
                        case 3:
                            break;
                        default:
                            break;
                    }
                }

                if (count > 0)
                {
                    var result = new AjaxResult("审核成功", AjaxResultType.Success);
                    return Token(result, "");
                }
                else
                {
                    var result = new AjaxResult("审核失败", AjaxResultType.Error);
                    return Token(result, "");
                }
            }
            catch (Exception ex)
            {
                var result = new AjaxResult("审核异常", AjaxResultType.Error);
                return Token(result, "");
            }

        }


    }
}
